#!/usr/bin/env python
# encoding: utf-8

import sys
import getopt
from GOToolKit.go_parser import *


help_message = '''
Usage '''+sys.argv[0]+''' [-hra] -g<goid> [-x<go_xml_file_path] [-o<obo_file_path]
-h: prints this message
-g: specify a GO id
-o: specify GO OBO file path
-x: specify GO XML path
-a: print ancestors
-r: recreate the dump file
'''

class Usage(Exception):
	def __init__(self, msg):
		self.msg = msg


def main(argv=None):
	goids = []
	xml_path = None
	dump_path = None
	obo_path = None
	recreate = False
	ancestors = False
	
	if argv is None:
		argv = sys.argv
	try:
		try:
			opts, args = getopt.getopt(argv[1:], "hg:x:d:rao:", ["help", "goid=" ,"xmlpath=", "dumppath=", "recreate", "ancestors", "obopath="])
		except getopt.error, msg:
			raise Usage(msg)
	
		for option, value in opts:
			if option in ("-h", "--help"):
				raise Usage(help_message)
			if option in ("-g", "--goid"):
				goids.append(value)
			if option in ("-x", "--xmlpath"):
				xml_path = value
			if option in ("-d", "--dumppath"):
				dump_path = value
			if option in ("-r", "--recreate"):
				recreate = True
			if option in ("-a", "--ancestors"):
				ancestors = True
			if option in ("-o", "--obopath"):
				obo_path = value
		
		if goids == []:
			raise Usage("GO ID required\n" + help_message)
		else:
			get_going(goids, xml_path, dump_path, obo_path, recreate, ancestors)
		
	except Usage, err:
		print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
		print >> sys.stderr, "for help use --help"
		return 2
		

def get_going(goids, xml_path, dump_path, obo_path, recreate, ancestors):
	print "got path", xml_path
	if obo_path:
		print "got obo path", obo_path
		go = go_parser(go_obo_filename=obo_path)
	elif xml_path:
		go = go_parser(go_xml_filename=xml_path, recreate=recreate)
	else:
		go = go_parser(recreate=recreate)
	for goid in goids:
		node = go.get_go_object(goid)
		if node == None:
			raise Usage("GO ID "+goid+" not found\n"+help_message)
		print "Go node information:"
		print "ID:", node['id']
		print "Name:", node['name']
		print "Namespace", node['namespace']
		print "Definition", node['definition']
		if ancestors:
			print "Ancestors:", ",".join([str(g) for g in go.get_ancestors(node['id'])])

if __name__ == "__main__":
	sys.exit(main())
